package com.hongri.recyclerview.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.hongri.recyclerview.R;
import com.hongri.recyclerview.activity.OnNewIntentTestActivity;
import com.hongri.recyclerview.bean.HotspotInfo;
import com.hongri.recyclerview.cache.CacheClearManager;
import com.hongri.recyclerview.cache.ImageWorker;
import com.hongri.recyclerview.receiver.HongriReceiver;
import com.hongri.recyclerview.service.HongriContext;
import com.hongri.recyclerview.utils.APPUtils;
import com.hongri.recyclerview.utils.CustomDialog;
import com.hongri.recyclerview.utils.Logger;
import com.hongri.recyclerview.utils.SnackbarUtil;
import com.hongri.recyclerview.utils.ToastUtil;

/**
 * @author：zhongyao on 2016/8/3 17:41
 * @description:
 */
public class SettingFragement extends Fragment implements View.OnClickListener {
    private static SettingFragement settingFragement;
    private static boolean hasClicked = false;
    private Activity mActivity;
    private Vibrator vibrator;
    private Button speechRecognizer;
    private ScrollView root_layout;
    private LinearLayout ll_clearCache, ll_convert;
    private Button vibrate;
    private Button ifelseBtn;
    private TextView tv_unbold, tv_bold;
    private RelativeLayout layout_toggle;
    private View toggle_layout;
    private FrameLayout layout_toggle_off, layout_toggle_on;
    private ProgressBar progress_off, progress_on;
    private ImageView iv_test;
    private ViewStub viewStub_test;
    private Button btnActivityTest;
    private Button urlQueryParamsTest;
    private Button btnOnNewIntent;
    private TextView tv_toast;
    private Button btn_receiver;
    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
    private boolean toggleOn = false, isloading = false;
    protected static final int SUCCESS_ON = 0, SUCCESS_OFF = 1, FAIL_ON = 2, FAIL_OFF = 3;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS_ON:
                    Logger.d("打开成功");
                    toggleSwitch(true, false);
                    break;
                case SUCCESS_OFF:
                    Logger.d("打开失败");
                    toggleSwitch(false, false);
                    break;
                case FAIL_ON:
                    Logger.d("关闭成功");
                    toggleSwitch(false, false);
                    break;
                case FAIL_OFF:
                    Logger.d("关闭失败");
                    toggleSwitch(true, false);
                    break;
            }

        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }

    public SettingFragement() {
    }

    public static SettingFragement getInstacne() {
        if (settingFragement == null) {
            synchronized (SettingFragement.class) {
                if (settingFragement == null) {
                    settingFragement = new SettingFragement();
                }
            }
        }
        hasClicked = false;
        return settingFragement;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initVibrate();

        testMethod();

        registerBroadcast();
    }

    private void registerBroadcast() {
        HongriReceiver receiver = new HongriReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(HongriReceiver.ACTION_RECEIVER);
        mActivity.registerReceiver(receiver, filter);
    }

    private void testMethod() {
        int i = 0;

        i++;

        Logger.d("i=" + i);
        Logger.d("i= " + i++);
        Logger.d("i=" + i);

        int j = 0;

        ++j;
        Logger.d("j=" + j);
        Logger.d("j=" + ++j);
        Logger.d("j=" + j);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //        initRecognizer();
    }

    private void initRecognizer() {
        PackageManager pm = mActivity.getPackageManager();
        List activities = pm.queryIntentActivities(new Intent(
            RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); // 本地识别程序
        // new Intent(RecognizerIntent.ACTION_WEB_SEARCH), 0); // 网络识别程序

        /*
         * 此处没有使用捕捉异常，而是检测是否有语音识别程序。
         * 也可以在startRecognizerActivity()方法中捕捉ActivityNotFoundException异常
         */
        if (activities.size() != 0) {
            speechRecognizer.setOnClickListener(this);
        } else {
            // 若检测不到语音识别程序在本机安装，测将扭铵置灰
            speechRecognizer.setEnabled(false);
            speechRecognizer.setText("未检测到语音识别设备");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        return initView(view);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        toggleOn = false;
        isloading = false;
        //        toggle_layout.setVisibility(View.GONE);
        toggleSwitch(toggleOn, isloading);
    }

    private View initView(View view) {
        root_layout = (ScrollView)view.findViewById(R.id.root_layout);
        ll_clearCache = (LinearLayout)view.findViewById(R.id.ll_clearCache);
        ll_convert = (LinearLayout)view.findViewById(R.id.ll_convert);
        vibrate = (Button)view.findViewById(R.id.vibrate);
        speechRecognizer = (Button)view.findViewById(R.id.speechRecognizer);
        ifelseBtn = (Button)view.findViewById(R.id.ifelseBtn);
        tv_unbold = (TextView)view.findViewById(R.id.tv_unbold);
        tv_bold = (TextView)view.findViewById(R.id.tv_bold);
        toggle_layout = view.findViewById(R.id.toggle_layout);
        layout_toggle = (RelativeLayout)view.findViewById(R.id.layout_toggle);
        layout_toggle_off = (FrameLayout)view.findViewById(R.id.layout_toggle_off);
        layout_toggle_on = (FrameLayout)view.findViewById(R.id.layout_toggle_on);
        progress_off = (ProgressBar)view.findViewById(R.id.progress_off);
        progress_on = (ProgressBar)view.findViewById(R.id.progress_on);
        iv_test = (ImageView)view.findViewById(R.id.iv_test);
        viewStub_test = (ViewStub)view.findViewById(R.id.viewStub_test);
        tv_toast = (TextView)view.findViewById(R.id.tv_toast);
        btn_receiver = (Button)view.findViewById(R.id.btn_receiver);
        btnActivityTest = (Button)view.findViewById(R.id.btnActivityTest);
        urlQueryParamsTest = (Button)view.findViewById(R.id.urlQueryParamsTest);
        btnOnNewIntent = (Button)view.findViewById(R.id.btnOnNewIntent);


        //viewStub_test.setVisibility(View.VISIBLE);
        //viewStub_test.inflate();
        /**
         * 当使用ViewStub方法setLayoutResource加载新的布局时，当调用setVisibility(View.VISIBLE)或inflate()才去加载新的布局;
         */
        viewStub_test.setLayoutResource(R.layout.toggle_layout);
        viewStub_test.setVisibility(View.VISIBLE);
        btnActivityTest.setOnClickListener(this);
        urlQueryParamsTest.setOnClickListener(this);
        btnOnNewIntent.setOnClickListener(this);
        //viewStub_test.inflate();

        ll_clearCache.setOnClickListener(this);
        ll_convert.setOnClickListener(this);
        vibrate.setOnClickListener(this);
        speechRecognizer.setOnClickListener(this);
        ifelseBtn.setOnClickListener(this);
        tv_bold.setOnClickListener(this);
        tv_unbold.setOnClickListener(this);
        layout_toggle.setOnClickListener(this);
        iv_test.setOnClickListener(this);
        tv_toast.setOnClickListener(this);
        btn_receiver.setOnClickListener(this);
        //        layout_toggle.setOnClickListener(this);
        //        layout_toggle_off.setOnClickListener(this);
        //        layout_toggle_on.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 缓存清理
             */
            case R.id.ll_clearCache:
                //                CacheClearManager.getInstance().clearCache();
                if (!hasClicked) {
                    hasClicked = true;
                    CacheClearManager.getInstance().cleanApplicationData(getActivity(), ImageWorker.bitmapPath);
                    ToastUtil.ShowBottomShort(getActivity(), R.string.clearCache);
                }
                break;
            /**
             * 多屏适配调研
             */
            case R.id.ll_convert:
                APPUtils.getPhoneInfo(getActivity());
                //                int dp = DisplayUtil.px2dip(getActivity(),24);
                //                int px = DisplayUtil.sp2px(getActivity(),13);
                //                ToastUtil.ShowBottomLong(getActivity(),"24px="+dp+"dp"+"  13sp="+px+"px");
                break;
            /**
             * 震动
             */
            case R.id.vibrate:
                startVibrate();
                break;
            /**
             * 语音识别
             */
            case R.id.speechRecognizer:
                //开始识别
                startRecognizerActivity();
                break;

            case R.id.ifelseBtn:

                String url = "haha";
                Logger.d(url);
                url = "hehe";
                Logger.d(url);
                int i = 3;
                if (i < 4) {
                    Logger.d("i<4");
                } else if (i < 5) {
                    Logger.d("i<5");
                } else if (i > 2) {
                    Logger.d("i>2");
                } else {
                    Logger.d("else");
                }

                Logger.d("==========");
                if (i > 4) {
                    Logger.d("i>4");
                } else if (i > 5) {
                    Logger.d("i>5");
                } else if (i > 2) {
                    Logger.d("i>2");
                } else {
                    Logger.d("else");
                }

                Logger.d("==========");
                if (i > 4) {
                    Logger.d("i>4");
                } else if (i > 5) {
                    Logger.d("i>5");
                } else if (i < 2) {
                    Logger.d("i<2");
                } else {
                    Logger.d("else");
                }

                //结论：只执行一个条件
                break;

            case R.id.tv_unbold:
                tv_unbold.setTypeface(Typeface.DEFAULT);
                tv_bold.setTypeface(Typeface.DEFAULT);
                break;
            case R.id.tv_bold:
                tv_unbold.setTypeface(Typeface.DEFAULT_BOLD);
                //                tv_bold.setTypeface(Typeface.DEFAULT_BOLD);
                tv_bold.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tv_bold.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));
                break;
            case R.id.layout_toggle:
                isloading = true;
                toggleSwitch(toggleOn, isloading);

                if (toggleOn) {
                    handler.sendEmptyMessageDelayed(SUCCESS_OFF, 2000);
                } else {
                    handler.sendEmptyMessageDelayed(SUCCESS_ON, 2000);
                }
                break;
            case R.id.layout_toggle_off:

                break;
            case R.id.layout_toggle_on:

                break;
            case R.id.iv_test:

                //iv_test.setImageResource(R.drawable.portrait_icon);
                //iv_test.setBackgroundResource(R.drawable.portrait_star_icon);
                iv_test.setScaleType(ScaleType.CENTER_CROP);
                break;
            //case R.id.viewStub_test:
            //    viewStub_test.setVisibility(View.VISIBLE);
            //    break;
            case R.id.tv_toast:
                //ToastUtil.ShowCustomToast(getActivity(), R.drawable.toast_check_icon, "已成功分享:", "搜索2018领取福利",
                //    R.color.gray, R.color.red,
                //    Toast.LENGTH_LONG, Gravity.CENTER);
                //ToastUtil.ShowCustomToast(getActivity(), "您已分享成功，记得到会员模块领取奖励噢", "会员", R.color.black, R.color.blue);

                CustomDialog customDialog = new CustomDialog(getActivity(), R.style.AppTheme);
                customDialog.showView(2000);

                SnackbarUtil.ShowSnackbar(getActivity(), root_layout);
                break;
            case R.id.btn_receiver:
                Intent intent_receiver = new Intent();
                intent_receiver.setPackage(mActivity.getPackageName());
                intent_receiver.setAction(HongriReceiver.ACTION_RECEIVER);
                HotspotInfo info = new HotspotInfo(1, "哈", "", "哈哈");
                intent_receiver.putExtra("object", info);
                mActivity.sendBroadcast(intent_receiver);
                break;
            case R.id.btnActivityTest:
                Activity topActivity = HongriContext.peekTopActivity();
                ToastUtil.ShowBottomShort(getActivity(), topActivity.getClass().getSimpleName() + "--");
                ArrayList<WeakReference<Activity>> activityLists = HongriContext.getActivityLists();
                for (WeakReference<Activity> activity :
                    activityLists) {
                    Logger.d("activity--:" + activity.get().getClass().getSimpleName() + "\n");
                }

                for (int j = 0; j < activityLists.size(); j++) {
                    Logger.d("activity:" + activityLists.get(j).get().getClass().getSimpleName() + "");
                }
                break;
            case R.id.urlQueryParamsTest:
                String mUrl = "youku://planet/weex?_wx_tpl=https://pre-wormhole.tmall.com/wow/planet/act/messagecomment?wh_showError=true&wh_weex=true&msg_account_id=4";

                Uri uri = Uri.parse(mUrl);
                String wh_weex = uri.getQueryParameter("wh_weex");
                String msg_account_id = uri.getQueryParameter("msg_account_id");

                ToastUtil.ShowBottomShort(getActivity(), "wh_weex:" + wh_weex + "msg_account_id:" + msg_account_id);

                break;
            case R.id.btnOnNewIntent:
                Intent intent = new Intent(getActivity(), OnNewIntentTestActivity.class);
                startActivity(intent);
                break;
            default:

                break;
        }
    }

    private void toggleSwitch(boolean toggleOn, boolean isloading) {
        if (toggleOn) {
            layout_toggle_on.setVisibility(View.VISIBLE);
            layout_toggle_off.setVisibility(View.GONE);
            if (isloading) {
                progress_on.setVisibility(View.VISIBLE);
            } else {
                progress_on.setVisibility(View.GONE);
            }

        } else {
            layout_toggle_on.setVisibility(View.GONE);
            layout_toggle_off.setVisibility(View.VISIBLE);
            if (isloading) {
                progress_off.setVisibility(View.VISIBLE);
            } else {
                progress_off.setVisibility(View.GONE);
            }

        }
    }

    private void startRecognizerActivity() {
        try {
            //通过Intent传递语音识别的模式，开启语音
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            //语言模式和自由模式的语音识别
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            //提示语音开始
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "speak now");
            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
            mActivity.startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
            ToastUtil.ShowBottomShort(mActivity, "未检测到语音设备...");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            ArrayList<String> results;
            results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            String resultString = "";
            for (int i = 0; i < results.size(); i++) {
                resultString += results.get(i);
            }
            ToastUtil.ShowBottomLong(mActivity, resultString);
        }
        super.onActivityResult(requestCode, resultCode, data);}

    private void stopVibrate() {
        vibrator.cancel();
    }

    private void startVibrate() {
        //震动1s
        vibrator.vibrate(1000);
    }

    private void initVibrate() {
        String vibratorService = Context.VIBRATOR_SERVICE;
        vibrator = (Vibrator)mActivity.getSystemService(vibratorService);
        //使用震动方式
        //       long[] pattern = {1000,2000,4000,8000,16000};
        //       vibrator.vibrate(pattern,0);
    }
}
